﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace FE.Applicaiton.Request
{
    public static class HttpHelper
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        private static string _timeout = System.Configuration.ConfigurationManager.AppSettings["timeout"]?.ToString();

        /// <summary>
        /// 请求操作处理
        /// </summary>
        /// <param name="uri">URI</param>
        /// <param name="title">操作标题</param>
        /// <param name="timeout">超时设置</param>
        /// <param name="writer">写发送数据回调</param>
        /// <param name="reader">读取返回数据回调</param>
        /// <returns>返回处理是否成功</returns>
        public static bool HandleWebRequest(string uri, string data)
        {
            bool result = false;

            //default 10分钟
            int timeout = 10 * 3600 * 1000;

            if (!string.IsNullOrEmpty(_timeout))
            {
                int t = 10;
                var ok = int.TryParse(_timeout, out t);

                if (ok)
                {
                    timeout = t * 3600 * 1000;
                }
            }

            try
            {
                WebRequest request = CreateRequest(uri, timeout);

                //WriteRequest(request, data);

                WriteFileToRequest(request, "d:fsdfsdfsdfsd");

                var res = ReadRequest(request);

                result = true;
            }
            catch (WebException e)
            {
                Logger.Error($"调用服务出错:{e.Message}");

                result = false;
            }
            catch (Exception e)
            {
                Logger.Error($"获取服务器出现异常:{e.Message}");
                result = false;
            }

            return result;
        }

        // <summary>
        /// 获取请求对象
        /// </summary>
        /// <param name="uri">URI</param>
        /// <param name="timeout">超时设置</param>
        /// <returns>返回请求对象</returns>
        private static WebRequest CreateRequest(string uri, int timeout)
        {
            WebRequest request = WebRequest.Create(uri);
            HttpWebRequest httpWebRequest = request as HttpWebRequest;
            if (httpWebRequest != null)
            {
                httpWebRequest.ServicePoint.ConnectionLimit = 200;
            }
            request.Proxy = null;
            request.Timeout = timeout;
            return request;
        }

        private static void WriteRequest(WebRequest request, string data)
        {
            request.Method = "POST";
            request.ContentLength = data.Length;
            request.ContentType = "application/json;charset=UTF-8";
            using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
            {
                sw.Write(data);
                //sw.Write(new object[] { });
            }
        }

        private static void WriteFileToRequest(WebRequest request, string filepath)
        {
            int fsLen = 0;
            //c#文件流读文件 
            using (FileStream fsRead = new FileStream(@"d:/tmp/pdf/123.pdf", FileMode.Open))
            {
                fsLen = (int)fsRead.Length;
                byte[] heByte = new byte[fsLen];
                int r = fsRead.Read(heByte, 0, heByte.Length);
                string myStr = System.Text.Encoding.UTF8.GetString(heByte);
                //Console.WriteLine(myStr);
                //Console.ReadKey();

                request.Method = "POST";
                request.ContentLength = filepath.Length;
                request.ContentType = "application/json;charset=UTF-8";
                using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
                {
                    sw.Write(heByte);
                    //sw.Write(new object[] { });
                }

            }





            //request.Method = "POST";
            //request.ContentLength = 1024;
            //request.ContentType = "application/json;charset=UTF-8";
            //using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
            //{
            //    sw.Write("");
            //    //sw.Write(new object[] { });
            //}


        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    

        private static string ReadRequest(WebRequest request)
        {
            string result = string.Empty;

            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    //StreamWriter sw = new StreamWriter(stream);
                    //sw.Write();

                    //stream.CopyTo();
                    //stream.

                  
                    FileStream fs = new FileStream(@"d:/tmp/pdf/222.docx", FileMode.OpenOrCreate);

                    var buffer = ReadFully(stream);
                    
                    fs.Write(buffer, 0, buffer.Length);
                    fs.Close();

                    //FileStream fs = new FileStream(stream);

                    //reader(stream);
                    //using (StreamReader sr = new StreamReader(stream))
                    //{

                    //    //result = sr.ReadToEnd();
                    //    //byte[] writeBytes = Encoding.UTF8.GetBytes(result);

                    //    //FileStream fsw = new FileStream(@"d:/tmp/pdf/1.docx", FileMode.OpenOrCreate);
                    //    //fsw.Write(writeBytes, 0, writeBytes.Length);
                    //    //fsw.Close();

                    //    var file = File.Create(@"d:/tmp/pdf/11.docx");
                    //    var w = file.CanWrite;
                    //    //file.
                    //    file.CopyTo(stream);
                    //}
                }

                

                response.Close();
            }

            

            return result;
        }

        private static string WriteFileToRequest(WebRequest request)
        {
            //c#文件流读文件 
            using (FileStream fsRead = new FileStream(@"d:/tmp/pdf/123.pdf", FileMode.Open))
            {
                int fsLen = (int)fsRead.Length;
                byte[] heByte = new byte[fsLen];
                int r = fsRead.Read(heByte, 0, heByte.Length);
                string myStr = System.Text.Encoding.UTF8.GetString(heByte);
                //Console.WriteLine(myStr);
                //Console.ReadKey();
            }

            return "";
        }
    }
}